﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PropertyManagementSystemAPI.Controllers
{
    /// <summary>
    /// 收费明细管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ChargesDetailInfoController : ControllerBase
    {
        IFreeSql db;
        public ChargesDetailInfoController(IFreeSql _db)
        {
            db = _db;
        }

        /// <summary>
        /// 查询收费明细全部数据
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">页条数</param>
        /// <param name="orealname">业主名称</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInfo(int page, int limit, string? orealname)
        {
            var list = db.Select<Models.Chargesdetailinfo, Models.Chargesinfo, Models.Ownerinfo>()
                .LeftJoin((a, b, c) => a.Chargesid == b.Chargesid && b.Isdelete == false)
                .LeftJoin((a, b, c) => a.Oid == c.Oid && c.Isdelete == false)
                .Where((a, b, c) => ((string.IsNullOrEmpty(orealname)) || (c.Orealname.Contains(orealname)) && (a.Isdelete == false)))
                .Count(out var total)
                .Page(page, limit)
                .ToList((a, b, c) => new
                {
                    a.Did,
                    a.Moneysum,
                    a.State,
                    a.Paytime,
                    a.Createtime,
                    a.Remark,
                    b.Chargesid,
                    b.ChargesName,
                    c.Oid,
                    c.Orealname
                });
            var json = new
            {
                code = 200,
                data = list,
                total = total,
            };
            return Ok(json);
        }

        /// <summary>
        /// 新增收费单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Add([FromBody] Models.Chargesdetailinfo info)
        {
            return Ok(new { });
        }

        /// <summary>
        /// 删除收费单
        /// </summary>
        /// <param name="did"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult Del(int? did)
        {
            try
            {
                int list = db.Update<Models.Chargesdetailinfo>(did)
                    .Set(x => x.Isdelete == true)
                    .ExecuteAffrows();
                return Ok(list > 0);
            }
            catch (Exception ex)
            {
                return Ok(false);
            }
        }
    }
}
